//
//  AppDelegate.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/21.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMAppDelegate.h"
#import <Aspects/Aspects.h>
#import <AFNetworking/AFNetworkReachabilityManager.h>
#import "YZMControllerManager.h"
#import "YZMUserService.h"
#import "YZMSeverTimeService.h"
#import "YZMLockPassword.h"
#import "YZMLockViewController.h"
#import "YZMNavigationController.h"
#import "YZMBankCardService.h"
#import "YZMStockSearchService.h"
#import "YZMyStocksService.h"
#import "YZMSuggestionService.h"
#import "YZMConfigureService.h"
#import <DateTools.h>
#import "Zhugeio/Zhuge.h"
#import "YZMPatchManager.h"
#import "YZMWebViewService.h"
//#import <UMMobClick/MobClick.h>
#import <UMSocialCore/UMSocialCore.h>
#import "YZMBundleVersionControlService.h"
#import "NSNumber+Utils.h"
#import <Bugly/Bugly.h>

@interface YZMAppDelegate ()

@end

@implementation YZMAppDelegate{
    
    BOOL _needGestureCheckFlag;
    BOOL _showGestureCheckFlag; /*是否正在显示手势校验页面*/
    UIImageView *_coverImageView;
    NSDate *_enterBgDate;/*进入后台时间*/
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:{
                
                if ([YZMUserService sharedService].validate) {
                
                    [YZMUserService sharedService].authorized = NO;
                }
                [YZMUserService stopBackgroundTask];
                
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi:
            case AFNetworkReachabilityStatusReachableViaWWAN:{
                
                [[YZMSeverTimeService sharedService] initSeverDate];
                [[YZMStockSearchService sharedService] checkIfNeedUpdateStocks];
                [YZMyStocksService sharedService];
                [[YZMConfigureService sharedService] checkIfNeedRequestConfigureWithSuccess:nil];
                [[YZMTDConfigureService sharedService] checkIfNeedRequestConfigureWithSuccess:nil];
                 [[YZMYLBConfigureService sharedService] checkIfNeedRequestConfigureWithSuccess:nil];
                [[YZMONEConfigureService sharedService] checkIfNeedRequestConfigureWithSuccess:nil];
                [[YZMFreeExperienceConfigureService sharedService]checkIfNeedRequestConfigureWithSuccess:nil];
                
                [[YZMBankCardService sharedService] initBankInfo];
                
                /*TODO:各种启动任务*/
                if (![YZMUserService sharedService].isValidate) {
                    
                    [[YZMUserService sharedService] login];
                    return;
                }
                
                [YZMUserService startBackgroundTask];
                break;
            }
            default:
                break;
        }
        
    }];
    
    [[YZMBundleVersionControlService sharedService] fecthBundVersion];
    do {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    } while (![[YZMBundleVersionControlService sharedService] isRun]);
    
    [YZMControllerManager initAndEnter];
    
#if defined(DEBUG_MODE)
    
#elif defined(TEST_MODE)
    /*诸葛IO*/
    Zhuge *zhuge = [Zhuge sharedInstance];
    [zhuge startWithAppKey:@"9d1bb7cce74c4f3299732d6c9eb9638b" launchOptions:launchOptions];
#else
    /*诸葛IO*/
    Zhuge *zhuge = [Zhuge sharedInstance];
    [zhuge startWithAppKey:@"d6d83614976f4ae1a13064436dc56627" launchOptions:launchOptions];
#endif
    
    _needGestureCheckFlag = YES;
    
    /*分享功能*/
#if defined(DEBUG_MODE) || defined(TEST_MODE)
    //打开调试日志
    [[UMSocialManager defaultManager] openLog:YES];
#endif
    NSString *configPath = [[NSBundle mainBundle] pathForResource:@"ConfigFile" ofType:@"plist"];
    NSDictionary *configDic = [NSDictionary dictionaryWithContentsOfFile:configPath];
    NSDictionary *UMengKey = configDic[@"UMeng"];
    NSDictionary *GeTuiDic = configDic[@"GeTui"];
    NSDictionary *qqDic = UMengKey[@"QQ"];
    NSDictionary *weChatDic = UMengKey[@"WeChat"];
    NSDictionary *sinaDic = UMengKey[@"Sina"];
    if (UMengKey[@"AppKey"]) {
        
#if defined(DEBUG_MODE) || defined(TEST_MODE)
        //友盟统计_测试用
//        UMConfigInstance.appKey = @"58b684616e27a42fd8000923";
#else
        //友盟统计_线上
//        UMConfigInstance.appKey = UMengKey[@"AppKey"];
#endif
//        [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    }
    
    //友盟分享
    if (UMengKey[@"ShareAppKey"]) {
        
        NSMutableArray *invalidArr = [NSMutableArray array];
        //设置友盟appkey
        [[UMSocialManager defaultManager] setUmSocialAppkey:UMengKey[@"ShareAppKey"]];
        if (qqDic) {
            //设置分享到QQ互联的appKey和appSecret
            [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:qqDic[@"AppKey"]  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
            [invalidArr addObject:@(UMSocialPlatformType_Qzone)];
        }
        
        if (weChatDic) {
            //设置微信的appKey和appSecret
            [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:weChatDic[@"AppKey"] appSecret:weChatDic[@"Secret"] redirectURL:@"http://mobile.umeng.com/social"];
            [invalidArr addObject:@(UMSocialPlatformType_WechatFavorite)];
        }
        
        if (sinaDic) {
            //设置新浪的appKey和appSecret
            [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:sinaDic[@"AppKey"]  appSecret:sinaDic[@"Secret"] redirectURL:@"http://sns.whalecloud.com/sina2/callback"];
        }
        
        if (invalidArr.count > 0) {
            //如果不想显示平台下的某些类型，可用以下接口设置
            [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:invalidArr];
        }
    }
    
    if (GeTuiDic) {
        
        //清除角标
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
        // [ GTSdk ]：是否允许APP后台运行
        [GeTuiSdk runBackgroundEnable:YES];
#if defined(DEBUG_MODE) || defined(TEST_MODE)
        
        [GeTuiSdk startSdkWithAppId:@"jthITbKQZA6kEAu9TQgCE9" appKey:@"u7byZmhbXL8NpSinR8pEm5" appSecret:@"LG5MJhuV9p7zr88MqRltfA" delegate:self];
#else
        //注册个推
        [GeTuiSdk startSdkWithAppId:GeTuiDic[@"AppID"] appKey:GeTuiDic[@"AppKey"] appSecret:GeTuiDic[@"AppSecret"] delegate:self];
#endif
        // 注册 APNs
        [self registerRemoteNotification];
    }
    [Bugly startWithAppId:@"f503bea916"];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    
    [[YZMControllerManager sharedManager] stopTimerTask];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    _needGestureCheckFlag = YES;
    [YZMUserService stopBackgroundTask];
    
    _enterBgDate = [NSDate date];
    
    if (_coverImageView == nil) {
        _coverImageView = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"LaunchImage"]];
        _coverImageView.frame = self.window.bounds;
    }
    [self.window addSubview: _coverImageView];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    [_coverImageView removeFromSuperview];
    
    [[YZMSeverTimeService sharedService] initSeverDate];
    
    if ([YZMUserService sharedService].currentUser) {
        
        [YZMUserService startBackgroundTask];
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    BOOL rechargeFlag = NO; //充值校验
    if ([YZMUserService sharedService].currentUser && [YZMLockPassword loadLockPassword]) {
        
        if (_needGestureCheckFlag  &&   (!_enterBgDate || [[NSDate date] timeIntervalSinceDate:_enterBgDate] > 2*60) ) {
            
            [application setStatusBarStyle:UIStatusBarStyleDefault];
            [self showLockViewController];
            rechargeFlag = YES;
        }
    }
    _needGestureCheckFlag = NO;
    
    [[YZMControllerManager sharedManager] startTimerTask];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
}

- (void)showLockViewController{
    
    
    if (_showGestureCheckFlag) {
        
        return;
    }
    
    _showGestureCheckFlag = YES;
    
    YZMLockViewController *lockVC = [[YZMLockViewController alloc] initWithType:YZM_LOCK_TYPE_FOR_CHECK];
    YZMNavigationController *presentedNav = [[YZMNavigationController alloc] initWithRootViewController:lockVC];
    [[YZMControllerManager sharedManager] presentViewController:presentedNav];
    
    _showGestureCheckFlag = NO;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    //跳转app内部方法
    BOOL result = [YZMWebViewService openAppMethodWithUrl:url];
    
    if (result) {
        
        return result;
    }
    
    //友盟分享回调
    result = [[UMSocialManager defaultManager] handleOpenURL:url];
    
    if (result) {
        
        return result;
    }
    
    return YES;
}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if (self.allowRotation) {
        return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskLandscapeLeft;
        }
    else {
        return (UIInterfaceOrientationMaskPortrait);
    }
}

#pragma mark - 用户通知(推送)
    
- (void)registerRemoteNotification {
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
}
    
    /** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", token);
    
    // 向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:token];
}
    
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    /// Background Fetch 恢复SDK 运行
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}
    
#pragma mark - APP运行中接收到通知(推送)处理 - iOS 10以下版本收到推送
    
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
    
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    //清除角标
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    if (!userInfo[@"localNoti_wcl"]) {
        // 将收到的APNs信息传给个推统计
        [GeTuiSdk handleRemoteNotification:userInfo];
    }
    completionHandler(UIBackgroundFetchResultNewData);
}
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    
    //  iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    
    NSLog(@"willPresentNotification：%@", notification.request.content.userInfo);
    //清除角标
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    // 根据APP需要，判断是否要提示用户Badge、Sound、Alert
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}
    
    //  iOS 10: 点击通知进入App时触发，在该方法内统计有效用户点击数
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSLog(@"didReceiveNotification：%@", response.notification.request.content.userInfo);
    //清除角标
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    if (!response.notification.request.content.userInfo[@"localNoti_wcl"]) {
        // [ GTSdk ]：将收到的APNs信息传给个推统计
        [GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
    }
    completionHandler();
}
    
#endif
    
#pragma mark - GeTuiSdkDelegate
    
    /** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    //个推SDK已注册，返回clientId
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
}
    
    /** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    //个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    NSLog(@"\n>>>[GexinSdk error]:%@\n\n", [error localizedDescription]);
}
    
    /** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    
    // 数据转换
    NSDictionary *payloadDic = nil;
    if (payloadData) {
        payloadDic = [NSJSONSerialization JSONObjectWithData:payloadData options:0 error:nil];
    }
    
    if (payloadDic && !offLine) {
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        //设置1秒之后
        NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:1];
        if (notification != nil) {
            // 设置推送时间
            notification.fireDate = pushDate;
            // 设置时区
            notification.timeZone = [NSTimeZone defaultTimeZone];
            // 设置重复间隔
            notification.repeatInterval = 0;
            // 推送声音
            notification.soundName = UILocalNotificationDefaultSoundName;
            // 推送内容
            notification.alertBody = payloadDic[@"msg"];
            //显示在icon上的红色圈中的数子
            notification.applicationIconBadgeNumber = 0;
            //设置userinfo 方便在之后需要撤销的时候使用
            NSDictionary *info = [NSDictionary dictionaryWithObject:@"onLineNoti"forKey:@"localNoti_wcl"];
            notification.userInfo = info;
            //添加推送到UIApplication
            UIApplication *app = [UIApplication sharedApplication];
            [app scheduleLocalNotification:notification];
        }
    }
}
    
    /** SDK运行状态通知 */
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
    // 通知SDK运行状态
    NSLog(@"\n>>[GTSdk SdkState]:%u\n\n", aStatus);
}

/** SDK设置推送模式回调 */
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
    if (error) {
        NSLog(@"\n>>[GTSdk SetModeOff Error]:%@\n\n", [error localizedDescription]);
        return;
    }
    
    NSLog(@"\n>>[GTSdk SetModeOff]:%@\n\n", isModeOff ? @"关闭" : @"开启");
    BOOL isOn = !isModeOff;
    [[NSUserDefaults standardUserDefaults] setBool:isOn forKey:@"isGeTuiModel"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refeshPushSwitch" object:self];
}

@end
